package com.go.where.manager.action.go;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.json.simple.JSONObject;

import com.go.where.manager.action.SuperAction;
import com.go.where.manager.common.Constants;
import com.go.where.manager.exception.ManagerException;
import com.go.where.manager.freemarker.CustomFreemarkerManager;
import com.go.where.manager.http.HttpClient;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.pojo.CourseInfo;
import com.go.where.manager.pojo.CourseRetrospectInfo;
import com.go.where.manager.service.CourseRetrospectService;
import com.go.where.manager.service.CourseService;
import com.go.where.manager.util.CommonUtil;
import com.go.where.manager.util.KindEditUtil;

@InterceptorRefs( {
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"image/bmp,image/png,image/gif,image/jpeg" }),
		@InterceptorRef(value = "defalutStackSet") })
public class CourseRetrospectAction extends SuperAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4383195694100314090L;
	private static final Logger log = Logger
			.getLogger(CourseRetrospectAction.class);

	public Pagination<?> page;

	@Resource(name = "courseRetrospectService")
	private CourseRetrospectService courseRetrospectService;
	@Resource(name = "courseService")
	private CourseService courseService;

	private CourseRetrospectInfo courseRetrospectInfo;
	private CourseRetrospectInfo courseRetrospectInfoQuery;

	private String retroId;
	private List<CourseInfo> courses;

	/**
	 * 查询列表
	 * 
	 * @return
	 */
	public String list() {
		if (courseRetrospectInfoQuery == null) {
			courseRetrospectInfoQuery = new CourseRetrospectInfo();
			courseRetrospectInfoQuery.setPageSize(Constants.INIT_PAGESIZE);
			courseRetrospectInfoQuery
					.setCurrentPage(Constants.INIT_CURRENTPAGE);
		}
		try {
			courseRetrospectInfoQuery.setIsDelete(Constants.NOT_DELETED);
			page = courseRetrospectService.queryPage(courseRetrospectInfoQuery);
		} catch (Exception e) {
			addActionError(e.getMessage());
			log.error("查询信息异常", e);
		}
		return LIST;
	}

	public String toEdit() {
		try {
			courseRetrospectInfo = courseRetrospectService
					.queryByPrimartKey(retroId);
			courses = courseService.queryAll();
			String htmlUrl = courseRetrospectInfo.getRetroContent();
			String ip = CustomFreemarkerManager.getValue("ip.url.prefix");
			if (StringUtils.isNotBlank(ip)) {
				htmlUrl = htmlUrl.replace(CustomFreemarkerManager.getValue(
						"ip.url.prefix.common").trim(), ip.trim());
			}
			HttpClient hc = new HttpClient();
			String htmlContent = hc.doGet(htmlUrl, "utf-8");
			String[] htmls = null;
			if (StringUtils.isNotBlank(htmlContent)) {
				htmls = htmlContent.split("<body>");
				if (htmls.length > 1) {
					String bodyHtmlStr = htmls[1];
					if (StringUtils.isNotBlank(bodyHtmlStr)) {
						String[] bodyHtmls = bodyHtmlStr.split("</body>");
						String body = bodyHtmls[0];
						courseRetrospectInfo.setRetroContent(this
								.htmlspecialchars(body));
					}
				}
			}
		} catch (Exception e) {
			addActionError("查询信息异常" + e.getMessage());
			log.error("查询信息异常", e);
		}
		return INPUT;
	}

	public String add() {
		courses = courseService.queryAll();
		return INPUT;
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public String save() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String savePath = ServletActionContext.getServletContext()
					.getRealPath(CommonUtil.FILE_SEPARATOR)
					+ Constants.MATERIAL_HTML;
			File htmlPath = new File(savePath);
			if (!htmlPath.exists()) {
				htmlPath.mkdirs();
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000) + ".html";
			String materialUrlPrefix = CustomFreemarkerManager
					.getValue("url.prefix");
			String htmlData = request.getParameter("content") != null ? request
					.getParameter("content") : "";
			log.info("获取富文本编辑器中内容：" + htmlData);
			htmlData = htmlData.replaceAll(Constants.PROJECT_NAME,
					materialUrlPrefix + Constants.PROJECT_NAME);
			log.info("替换后的内容：" + htmlData);
			if (StringUtils.isNoneBlank(courseRetrospectInfo.getCourseName())) {
				String[] idName = courseRetrospectInfo.getCourseName().split(
						",");
				courseRetrospectInfo.setCourseId(idName[0]);
				courseRetrospectInfo.setCourseName(idName[1]);
			}
			StringBuilder sb = KindEditUtil.linkHtml(htmlData,
					courseRetrospectInfo.getCourseName(), true);

			CommonUtil.createHtml(sb.toString(), savePath + newFileName);

			courseRetrospectInfo.setRetroContent(materialUrlPrefix
					+ Constants.PROJECT_NAME + CommonUtil.FILE_SEPARATOR
					+ Constants.MATERIAL_HTML + newFileName);
			
			courseRetrospectService.save(courseRetrospectInfo,
					getCurrentOperator());
			redirectionUrl = "course_retrospect!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存信息异常", e);
			addActionError("保存信息异常！" + e);
			return this.add();
		}
	}

	/**
	 * 编辑
	 * 
	 * @return
	 */
	public String edit() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String savePath = ServletActionContext.getServletContext()
					.getRealPath(CommonUtil.FILE_SEPARATOR)
					+ Constants.MATERIAL_HTML;
			String[] htmlArr = courseRetrospectInfo.getRetroContent()
					.split("/");
			String newFileName = htmlArr[htmlArr.length - 1];
			String materialUrlPrefix = CustomFreemarkerManager
					.getValue("url.prefix");
			String htmlData = request.getParameter("content") != null ? request
					.getParameter("content") : "";
			htmlData = htmlData.replaceAll(materialUrlPrefix
					+ Constants.PROJECT_NAME, Constants.PROJECT_NAME);
			htmlData = htmlData.replaceAll(Constants.PROJECT_NAME,
					materialUrlPrefix + Constants.PROJECT_NAME);
			StringBuilder sb = KindEditUtil.linkHtml(htmlData,
					courseRetrospectInfo.getCourseName(), false);

			CommonUtil.createHtml(sb.toString(), savePath + newFileName);
			courseRetrospectInfo.setRetroContent(materialUrlPrefix
					+ Constants.PROJECT_NAME + CommonUtil.FILE_SEPARATOR
					+ Constants.MATERIAL_HTML + newFileName);
			if (StringUtils.isNoneBlank(courseRetrospectInfo.getCourseName())) {
				String[] idName = courseRetrospectInfo.getCourseName().split(
						",");
				courseRetrospectInfo.setCourseId(idName[0]);
				courseRetrospectInfo.setCourseName(idName[1]);
			}
			courseRetrospectService.update(courseRetrospectInfo,
					getCurrentOperator());
			redirectionUrl = "course_retrospect!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("修改信息异常", e);
			addActionError("修改信息异常！" + e);
			retroId = courseRetrospectInfo.getRetroId();
			return this.toEdit();
		}
	}

	public String falseDelete() {
		courseRetrospectInfo = new CourseRetrospectInfo();
		courseRetrospectInfo.setRetroId(retroId);
		courseRetrospectInfo.setIsDelete(Constants.DELETED);
		try {
			courseRetrospectService.update(courseRetrospectInfo,
					getCurrentOperator());
			redirectionUrl = "course_retrospect!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("删除信息异常", e);
			addActionError("删除信息异常" + e);
			return this.list();
		}
	}

	/**
	 * 富文本编辑器里上传图片
	 * 
	 * @return
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public String imgUpload() throws FileUploadException, IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		String obj = "";
		try {
			obj = KindEditUtil.uploadImage(request, response, out,
					Constants.RETROSPECT_IMAGES);
		} catch (ManagerException e) {
			return e.getMessage();
		}
		// log.info(saveUrl);
		// 在编辑框内生成图片
		out.print(obj);
		return null;
	}

	/**
	 * 图片文件管理
	 * 
	 * @return
	 * @throws Exception
	 */
	public String fileManager() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();

		JSONObject result = new JSONObject();
		try {
			result = KindEditUtil.fileManager(request, out,
					Constants.RETROSPECT_IMAGES);
		} catch (ManagerException e) {
			return null;
		}

		response.setContentType("application/json; charset=UTF-8");
		out.println(result.toJSONString());
		return null;
	}

	private String htmlspecialchars(String htmlStr) {
		htmlStr = htmlStr.replaceAll("&", "&amp;");
		htmlStr = htmlStr.replaceAll("<", "&lt;");
		htmlStr = htmlStr.replaceAll(">", "&gt;");
		htmlStr = htmlStr.replaceAll("\"", "&quot;");
		return htmlStr;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public String getRetroId() {
		return retroId;
	}

	public void setRetroId(String retroId) {
		this.retroId = retroId;
	}

	public CourseRetrospectInfo getCourseRetrospectInfo() {
		return courseRetrospectInfo;
	}

	public void setCourseRetrospectInfo(
			CourseRetrospectInfo courseRetrospectInfo) {
		this.courseRetrospectInfo = courseRetrospectInfo;
	}

	public CourseRetrospectInfo getCourseRetrospectInfoQuery() {
		return courseRetrospectInfoQuery;
	}

	public void setCourseRetrospectInfoQuery(
			CourseRetrospectInfo courseRetrospectInfoQuery) {
		this.courseRetrospectInfoQuery = courseRetrospectInfoQuery;
	}

	public List<CourseInfo> getCourses() {
		return courses;
	}

	public void setCourses(List<CourseInfo> courses) {
		this.courses = courses;
	}

}
